package com.example.everying.controller.points;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.everying.annotation.WebLog;
import com.example.everying.context.UserContext;
import com.example.everying.model.entity.user.ActivityPointsConfig;
import com.example.everying.model.vo.officialNotice.FilePathVo;
import com.example.everying.model.vo.user.SignRewardVO;
import com.example.everying.model.vo.points.ActivityPointsConfigListVo;
import com.example.everying.model.vo.user.UserInfoVo;
import com.example.everying.service.user.ActivityPointsConfigService;
import com.example.everying.utils.PageParam;
import com.example.everying.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.management.Query;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Wrapper;
import java.util.ArrayList;
import java.util.List;

@RestController
@Api(tags = "活动积分配置")
@RequestMapping("/points")
public class ActivityPointsConfigController {

    @Value("${pointActivityPath}")
    private String pointActivityPath;

    @Value("${pointActivityUrlPrefix}")
    private String pointActivityUrlPrefix;

    @Autowired
    private ActivityPointsConfigService activityPointsConfigService;

    //条件查询带分页
    @ApiOperation(value = "分页查询")
    @PostMapping("/page")
    public Result<?> page(@RequestBody PageParam<ActivityPointsConfig> query) {
        Page<ActivityPointsConfig> pageParam = new Page<>(query.getPage(), query.getLimit());
        IPage<ActivityPointsConfig> pageModel = activityPointsConfigService.selectPage(pageParam, query.getQuery());
        return Result.ok(pageModel);
    }
    //条件查询带分页
    @ApiOperation(value = "活动列表")
    @PostMapping("/activity/list")
    public Result<?> list() {
        UserInfoVo user = UserContext.getUser();
        if (user == null) {
            return Result.fail("用户未登录");
        }
        List<ActivityPointsConfigListVo> pageModel = activityPointsConfigService.selectActivityList(user.getId());
        return Result.ok(pageModel);
    }
    @PostMapping("/add")
    @WebLog(description = "添加活动积分配置")
    public Result<?> add(@ApiParam(name = "ActivityPointsConfig", value = "积分配置", required = true)
                             @RequestBody ActivityPointsConfig config){
        return activityPointsConfigService.add(config);
    }
    @PostMapping("/update")
    @WebLog(description = "修改活动积分配置")
    public Result<?> update(@ApiParam(name = "ActivityPointsConfig", value = "积分配置", required = true)
                         @RequestBody ActivityPointsConfig config){
        return activityPointsConfigService.update(config);
    }

    /**
     * 查询用户今天的连续签到天数
     * @return 连续签到天数（如3表示今天是连续第3天）
     */
    @PostMapping("/todayContinuousDays")
    @WebLog(description = "查询用户今天的连续签到天数")
    public Result<List<SignRewardVO>> getTodayContinuousDays() {
        List<SignRewardVO> todayContinuousDays = activityPointsConfigService.getTodayContinuousDays(UserContext.getUser().getId());
        return Result.ok(todayContinuousDays);
    }

    /**
     * 用户签到接口
     * @param continuousDays 连续签到天数
     * @return 签到结果
     */
    @GetMapping("/reward")
    @WebLog(description = "用户签到")
    public Result<String> signReward(@RequestParam("continuousDays") int continuousDays) {
        String userId = UserContext.getUser().getId();
        boolean success = activityPointsConfigService.handleSignReward(userId, continuousDays);
        return success ? Result.success("签到成功") : Result.fail("已签到");
    }

    @ApiOperation("获取轮播图信息")
    @WebLog(description = "获取轮播图信息")
    @PostMapping("/getCarouselImage")
    public Result<?> getCarouselImage() {

        return activityPointsConfigService.getCarouselImage();
    }



    /**
     * 上传活动页到服务器
     * @param file
     * @return
     */
    @ApiOperation("上传活动页")
    @PostMapping("/uploadActivity")
    @WebLog(description = "上传活动页")
    public Result<?> uploadActivity(@RequestParam("file") MultipartFile file){
        if (file == null){
            return Result.fail("上传文件为空");
        }
        // 获取文件后缀
        String originalFilename = file.getOriginalFilename();
        String suffix = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        }

        // 校验后缀只能是 .html
        if (!".html".equals(suffix)) {
            return Result.fail("只能上传 HTML 文件");
        }

        try {
            Path uploadPath = Paths.get(pointActivityPath);
            if (!Files.exists(uploadPath)){
                Files.createDirectories(uploadPath);
            }
            String fileName = System.currentTimeMillis() + "_" + originalFilename;
            Path filePath = uploadPath.resolve(fileName);
            Files.copy(file.getInputStream(),filePath);
            FilePathVo filePathVo = new FilePathVo();
            filePathVo.setActivityPath(filePath.toString());
            filePathVo.setFileName(fileName);
            filePathVo.setActivityUrl(pointActivityUrlPrefix + fileName);


            return Result.ok(filePathVo);
        }catch (IOException e){
            e.printStackTrace();
            return Result.fail("上传文件失败");
        }

    }

}
